<template>
  <div class="list">
    <!-- :label-col="{span: 5}"-->
    <a-form
        ref="searchFormRef"
        class="search-form base-mb15"
        :label-col="{ style: { minWidth: '100px' } }"
        :model="searchFormState"
        @finish="onSearchFinish"
    >
      <a-row :gutter="[10, 24]">
        <a-col :span="6">
          <a-form-item name="mobile" :label="$t('self.order.tips2')">
            <a-input v-model:value="searchFormState.mobile"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="orgId" :label="$t('self.order.tips12')">
            <a-select v-model:value="searchFormState.orgId" :options="searchOrgOptions" :fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="orderNo" :label="$t('self.order.tips13')">
            <a-input v-model:value="searchFormState.orderNo"></a-input>
          </a-form-item>
        </a-col>
<!--        <a-col :span="6">-->
<!--          <a-form-item name="stationId" :label="$t('self.order.tips5')">-->
<!--            <a-input v-model:value="searchFormState.stationId"></a-input>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
<!--      </a-row>-->
<!--      <a-row :gutter="[10, 24]" class="base-mt20">-->
        <a-col :span="6">
          <a-form-item name="startTime" :label="$t('self.order.tips14')">
            <a-date-picker v-model:value="searchFormState.startTime" style="width: 100%;"/>
          </a-form-item>
        </a-col>

        <a-col :span="6">
          <a-form-item name="endTime" :label="$t('self.order.tips15')">
            <a-date-picker v-model:value="searchFormState.endTime" style="width: 100%;"/>
          </a-form-item>
        </a-col>

<!--        <a-col :span="6">-->
<!--          <a-form-item name="orderType" :label="$t('self.order.tips17')">-->
<!--            <a-select v-model:value="searchFormState.orderType" :options="searchOrderTypeOptions" :placeholder="$t('self.pleaseChoose')"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :span="6">-->
<!--          <a-form-item name="status" :label="$t('self.order.tips16')" :label-col="{ style: { width: '100px' } }">-->
<!--            <a-select v-model:value="searchFormState.status" :options="searchStatusOptions" :placeholder="$t('self.pleaseChoose')"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

        <a-col :span="6" offset="1" class="base-flex base-rows">
          <a-button type="primary" html-type="submit">{{ $t('self.searchButton') }}</a-button>
          <a-button class="base-ml10" @click="resetSearchForm">{{ $t('self.resetButton') }}</a-button>
        </a-col>
      </a-row>

    </a-form>

    <s-table ref="stableRef" :api-obj="tableConfig.apiObj" api-method="POST" :columns="sourceColumn" row-key="id" :light-index="tableConfig.lightIndex" :params="{ status: searchFormState.status}" :is-row-selection="false" @selectionChange="tableSelectionChange" :is-show-tool="false" :scroll="{ x: 2200 }">
      <template #bodyCell="{ column, record, index }">

        <!--帐户状态-->
        <template v-if="column.key === 'status'">
          <template v-if="record[column.key]">
            <sc-status-indicator type="primary"></sc-status-indicator>
            {{ $t('self.user.tips6') }}
          </template>
          <template v-else>
            <sc-status-indicator type="warning"></sc-status-indicator>
            {{ $t('self.user.tips7') }}
          </template>
        </template>

        <template v-if="column.key === 'action'">
          <span>
            <a href="javascript:void(0)" @click="openDetailModal(record, index)">{{ $t('self.detailView') }}</a>
          </span>
          <a-divider type="vertical"/>

          <a-popconfirm
              :title="$t('self.order.tips58')"
              :ok-text="$t('self.yesTxt')"
              :cancel-text="$t('self.noTxt')"
              @confirm="handleSettle(record, index)"
          >
            <a href="javascript:void(0)">{{ $t('self.order.tips57') }}</a>
          </a-popconfirm>

        </template>

      </template>
    </s-table>

    <detailModal ref="detailModalRef" @ok="" @close=""></detailModal>

  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
import detailModal from './detail_modal.vue'
import { useRoute, useRouter } from 'vue-router'
import ScStatusIndicator from '@/components/scMini/scStatusIndicator.vue'
import { mainStore } from '@/stores/mainStore'

const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t
const route = useRoute()
const router = useRouter()
const useMainStore = mainStore()

const selectedKey = ref([])
const stableRef = ref(null)
const tableConfig = ref({
  apiObj: $API.backend.order.list,
  lightIndex: [] // 要高亮的行号
})
// 表格列
const sourceColumn = ref([])

onMounted(async () => {
  // 获取表格列
  resetDefaultOptionsByLang()
  // 获取运营商下拉数据
  searchOrgOptions.value = await proxy.getOrgSelectList(true)
})

// 监听 lang 状态
watch(
    () => useMainStore.lang, // 切换语言包时
    (curr, old) => {
      // console.log('语言包', curr)
      // 获取表格列
      resetDefaultOptionsByLang()
    }
)

const resetDefaultOptionsByLang = () => {
  sourceColumn.value = [
    {
      title: $T('self.order.tips210'),
      dataIndex: 'orderNo',
      key: 'orderNo'
    },
    {
      title: $T('self.stationMap.tips77'),
      dataIndex: 'orgName',
      key: 'orgName'
		},
    {
      title: $T('self.order.tips207'),
      dataIndex: 'stationName',
      key: 'stationName'
		},
    {
      title: $T('self.order.tips204'),
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: $T('self.order.tips205'),
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: 'CITY | COUNTRY',
      dataIndex: 'city',
      key: 'city',
      customRender: ({record}) => {
			  return (record.city + '-' + record.country);
		  },
    },
    // {
    //   title: $T('self.order.tips5'),
    //   dataIndex: 'pileNo',
    //   key: 'pileNo'
    // },
    {
      title: $T('self.businessStation.modal.col15'),
      dataIndex: 'vehicle',
      key: 'vehicle',
      customRender: ({text}) => {
        return (text == 1 ? "E-CARS":"MOTOS");
      },
    },
    {
      title: $T('self.order.tips208'),
      dataIndex: 'currentV',
      key: 'currentV'
    },
    {
      title: $T('self.order.tips209'),
      dataIndex: 'currentA',
      key: 'currentA'
    },
    {
      title: $T('self.order.tips203'),
      dataIndex: 'totalChargeQuantity',
      key: 'totalChargeQuantity',
      // 自定义显示列
      customRender: ({text, record}) => {
        // 将 text 转换为数值类型
        const numericValue = parseFloat(text);
        if (isNaN(numericValue)) return ''; // 如果不是有效的数值，则返回空字符串
        // 除以1000并保留最多2位小数
        return (numericValue / 1000).toFixed(2);
      },
    },
    {
      title: $T('self.order.tips214'),
      dataIndex: 'totalChargeTimes',
      key: 'totalChargeTimes',
      // 自定义显示列
      customRender: ({text, record}) => {
        // 接口返回是秒，处理为分
        return proxy.getMinBySeconds(text)
      },
    },
    {
      title: $T('self.order.tips215'),
      dataIndex: 'totalChargeMoney',
      key: 'totalChargeMoney'
    },
    {
      title: $T('self.userCharge.tips15'),
      dataIndex: 'keyfob',
      key: 'keyfob'
    },
    { title: $T('self.actionButton'), key: 'action', ellipsis: true, fixed: 'right', width: 150 }
  ]
  searchOrderTypeOptions.value = [
    {
      label: $T('self.order.orderType.all'),
      value: ''
    },
    {
      label: $T('self.order.orderType.tips1'),
      value: 1
    },
    {
      label: $T('self.order.orderType.tips2'),
      value: 2
    },
    {
      label: $T('self.order.orderType.tips3'),
      value: 3
    },
    {
      label: $T('self.order.orderType.tips4'),
      value: 4
    },
    {
      label: $T('self.order.orderType.tips5'),
      value: 5
    }
  ]
  // 充电中：2
  // 充电结束（待结算）：3
  // 已结算：4
  // 已结束（非正常充电结束）5
  // 历史订单：1
  searchStatusOptions.value = [
    {
      label: $T('self.order.statusType.all'),
      value: ''
    },
    {
      label: $T('self.order.statusType.tips1'),
      value: 3
    },
    {
      label: $T('self.order.statusType.tips2'),
      value: 4
    },
    {
      label: $T('self.order.statusType.tips3'),
      value: 5
    },
    {
      label: $T('self.order.statusType.tips4'),
      value: 1
    },
  ]
}

const tableSelectionChange = (rows, record) => {
  selectedKey.value = rows
  // console.log('表格选择项', rows, record)
}

// =========start search表单
const searchFormRef = ref(null)
// 参数status:
// 充电结束（待结算）：3
// 已结算：4
// 已结束（非正常充电结束）5（包含充电中）
// 历史订单：1
const searchFormState = ref({
  mobile: '',     // 手机号码
  orderNo: '',    // 订单号
  orgId: null,    // 运营商及场站
  stationId: '',   // 充电桩号
  startTime: '',  // 开始时间
  endTime: '',    // 开始时间
  status: 2,   // 状态
})
const searchOrgOptions = ref([])
const searchOrderTypeOptions = ref([])
const searchStatusOptions = ref([])
const onSearchFinish = (values) => {
  values.orgId = values.orgId?values.orgId: ''
  stableRef.value.upData(values, 1)
}
// 重置搜索表单
const resetSearchForm = () => {
  searchFormRef.value.resetFields()
}
// =========end search表单

const detailModalRef = ref(null)
const openDetailModal = (record, index) => {
  tableConfig.value.lightIndex = [index] // 仅高亮当前行
  nextTick(() => {
    detailModalRef.value.show(record)
  })
}

const handleSettle = (record, index) => {
  const params = {
    orderNo: record.orderNo
  }
  $API.backend.order.settle.get(params).then(res => {
    stableRef.value.refresh()
  }).catch(() => {

  })
}

</script>

<style lang="scss" scoped>
.list {
  height: 100%;
  background: #ffffff;
  padding: 15px;

  .search-form {
    padding: 16px;
    background: rgb(247, 248, 250);

    :deep(.ant-form-item) {
      margin-bottom: 0;
    }
  }
}
</style>
